<?PHP

require_once WACT_ROOT . 'db/db.inc.php';
require_once WACT_ROOT .'util/arraydataset.inc.php';
require_once WACT_ROOT .'util/dataspace.inc.php';
require_once APP_ROOT.'model/common/date.php';
require_once APP_ROOT.'model/common/site.php';

class LeftMenuModel {

	function LeftMenuModel(){
	}

	function &getTypesList() {
		$typesArray = array('1'=>'Text header','2'=>'Text link','3'=>'Image header','4'=>'Image link','5'=>'Hot Text link' );
		return $typesArray;
	}

	function &getTypeName($i) {
    	$typesArray =& LeftMenuModel::getTypesList();
    	return $typesArray[$i];
	}

    function &getLocationsList() {
		$typesArray = array('1'=>'Left menu','2'=>'Right menu above columnists','3'=>'Right menu under columnists','4'=>'Top Left Hot links');
		return $typesArray;
	}

    function &getLocationName($i) {
    	$lArray =& LeftMenuModel::getLocationsList();
    	return $lArray[$i];
	}


	function &getCurDate() {
		$mytime =& new MyTimeZone();
		$ts = $mytime->timeNowLocal();
		$now=getdate($ts);
		$month = $now['month'];
		//$month = sprintf("%02d",$month);
        $mday = $now['mday'];
		//$month = sprintf("%d",$mday);
        $year = $now['year'];
		//$month = sprintf("%02d",$month);
        $hours = $now['hours'];
        $minutes = $now['minutes'];
        $minutes = sprintf("%02d",$minutes);

		$curdate=$month.' '.$mday.', '.$year.' '.$hours.':'.$minutes;
		return $curdate;
	}

    function &getRecord($id) {
        return DBC::FindRecord("SELECT M.*
        FROM sport_menu M
        WHERE M.menu_id = ". DBC::makeLiteral($id));
    }

    function delete($id) {
        DBC::execute("DELETE FROM sport_menu WHERE menu_id=". DBC::makeLiteral($id));
    }

	function &getLeftMenuList($location) {
		$typesArray=array('1'=>'txt','txtlink','img','imglink','hotlink');
		$rootItems=&LeftMenuModel::getRootItemList($location);
		$subItems=&LeftMenuModel::getSubItemList($location);
		$rootItems->reset();
		$subItems->reset();
		$i=1;
		$menuArray=array();

		$next=$subItems->next();
		while($rootItems->next()){
			$type=$rootItems->get('type');
			$external = $rootItems->get('external');
			if($i%2!=0) $style="light";
			else $style="dark";

			$menu_id = $rootItems->get('menu_id');
			$subArray=array('root_'.$typesArray[$type]=>'1');
			$subArray=array_merge($subArray,array('style'=>$style));

			$fieldsArray=$rootItems->getPropertyList();
			foreach($fieldsArray as $index=>$property){
					if($property=='title'||$property=='url'||$property=='image'||true)
						$subArray=array_merge($subArray,array($property=>$rootItems->get($property)));
      		}
            if ($external) {
            	//$myarray=array('external_show'=>'1');
            	//$subArray=array_merge($subArray,$myarray);
            	$subArray['external_show']=1;
            }
      		$menuArray=array_merge($menuArray,array($subArray));

            $j=1;
            $substyle_end = "light_submit";
			while($next && $subItems->get('parent_id') == $menu_id) {
				$type = $subItems->get('type');
				$external = $subItems->get('external');
				$submenu_id = $subItems->get('menu_id');
                $suborder = $subItems->get('order');
                $is_last = false;
                $nextitem =& LeftMenuModel::getNextMenuItem($suborder, $menu_id, $submenu_id, $location);
                $is_last = is_null($nextitem);
                if ($is_last || !$nextitem) {
                	if($i%2!=0) $style="light_submit";
					else $style="dark_submit";
				} else if ($nextitem) {
                    if($i%2!=0) $style="light";
					else $style="dark";
					//print_r($nextitem);
					//print $nextitem['menu_id'].' '.$nextitem['title'];
				}
                if ($i%2!=0) { $light = 1; $dark = 0; }
				else { $dark = 1;  $light = 0; }

                //if($j%2!=0) $substyle="light";
				//else $substyle="dark";
                if($j%2!=0) $substyle_end = "light_submit";
				else $substyle_end = "dark_submit";
				$subArray=array('sub_'.$typesArray[$type]=>'1');

				foreach($fieldsArray as $index=>$property){
					if($property=='title'||$property=='url'||$property=='image'||true)
						$subArray=array_merge($subArray,array($property=>$subItems->get($property)));
      			}
      			if ($external) $subArray['external_show'] = 1;
                $subArray['style'] = $style;
                if ($dark) $subArray['dark'] = $dark;
                if ($light) $subArray['light'] = $light;
				$menuArray=array_merge($menuArray,array($subArray));
				$next=$subItems->next();
				$j++;
			}

			if($i%2==0) $subArray = array('end_odd'=>'1','style'=>$substyle_end);
			else $subArray = array('end_even'=>'1','style'=>$substyle_end);

			$menuArray=array_merge($menuArray,array($subArray));
			$i++;

		}

		$menuList=new ArrayDataSet($menuArray);
		//print_r( $menuList );
		return $menuList;
	}

	function &getRootItemList($location) {
		$site_id = Site::getSiteID();
		$query = "select menu_id, title, url,image,type,enable,external, menu_location, site_id
		from sport_menu
		where enable=1
		and parent_menu_id = 0
        and menu_location = ".DBC::makeLiteral($location)."
        and site_id = ".DBC::makeLiteral($site_id)."
		order by `order` ";
		$result =& DBC::NewRecordSet($query);
		return $result;
	}

    function &getRootMenusForCombo($location, $exclude_id=0) {
    	$rs =& LeftMenuModel::getRootItemList($location);
        $rs->reset();
        $menus = array();
        $menus[0] = '(None)';
        while($rs->next()) {
        	$menu_id = $rs->get('menu_id');
        	$title = $rs->get('title');
        	if ($menu_id != $exclude_id) $menus[$menu_id] = $title;
        }

        return $menus;
	}



	function &getSubItemList($location) {
		$site_id = Site::getSiteID();
		$query = "select a.menu_id, a.parent_menu_id as parent_id, a.external,
		a.title, a.url, a.image, a.type, a.enable, a.`order`, P.headline, a.page_id, a.site_id
		from sport_menu a inner join sport_menu b
		on a.parent_menu_id = b.menu_id
		left outer join sport_static_pages P
		on a.page_id = P.page_id
		where a.enable=1 and b.enable=1
		and a.menu_location = b.menu_location
		and a.menu_location = ".DBC::makeLiteral($location)."
		and a.site_id = ".DBC::makeLiteral($site_id)."
        and b.site_id = ".DBC::makeLiteral($site_id)."
        order by b.order, a.order ";
		$result =& DBC::NewRecordSet($query);
		return $result;
	}

	function &getChildMenuItems($parent_menu_id) {
		$site_id = Site::getSiteID();
        $sql = "select P.headline, M.*
		from sport_menu M
		left outer join sport_static_pages P
		on M.page_id = P.page_id
		where M.parent_menu_id = ".DBC::makeLiteral($parent_menu_id)."
        and M.site_id = ".DBC::makeLiteral($site_id)."
		order by M.`order` ";
		$result =& DBC::NewRecordSet($sql);
		return $result;
	}

    function &getAllMenuItems($location) {
    	$site_id = Site::getSiteID();
		$sql = "select P.headline, M.*
		from sport_menu M
		left outer join sport_static_pages P
		on M.page_id = P.page_id
		where M.parent_menu_id = 0
		and M.menu_location = ".DBC::makeLiteral($location)."
		and M.site_id = ".DBC::makeLiteral($site_id)."
		order by M.`order` ";
		$result =& DBC::NewRecordSet($sql);

		//$rootArray = $result->exportDataSetAsArray();


        $list_updated=array();
        $result->reset();
        $rootLength = $result->getRowCount();
        $i = 0;
        while ($result->next()) {
        	  $dataspace =& $result->export();
        	  $menu_id = $result->get('menu_id');
        	  $title =  $result->get('title');
              $parent_menu_id = $result->get('parent_menu_id');

              if ($i==0) $dataspace['first_item'] =  1;
              elseif ($i == $rootLength-1) $dataspace['last_item'] =  1;
              if ($rootLength == 1) $dataspace['last_item'] =  1;
              $dataspace['index'] =  $i.'/'.$rootLength;
              $list_updated[$menu_id] = $dataspace;
              //Print "ROOT: ".$menu_id.' '.$title.'<br>';



              $childresult =& LeftMenuModel::getChildMenuItems($menu_id);
              //$childArray = $childresult->exportDataSetAsArray();

              $childresult->reset();
              $childLength = $childresult->getRowCount();
              $j=0;
        	  while ($childresult->next()) {
        	  		$childdataspace =& $childresult->export();
        	  		$childmenu_id = $childresult->get('menu_id');
        	  		$childtitle =  $childresult->get('title');
                    if ($j==0) $childdataspace['first_item'] =  1;
              		elseif ($j==$childLength-1) $childdataspace['last_item'] =  1;
              		if ($childLength == 1) $childdataspace['last_item'] =  1;
                    $childdataspace['index'] =  $j.'/'.$childLength;
                    $list_updated[$childmenu_id] = $childdataspace;
                    //print _r($childdataspace);  print '<br>';
                    //Print "    CHILD: ".$childmenu_id.' '.$childtitle.'<br>';
                    $j++;
        	  }
        	  $i++;
        }

        $dataset =& new ArrayDataSet($list_updated);
		return $dataset;
	}

    function insertMenu(&$data) {
        $site_id = Site::getSiteID();
        $data->set('site_id',$site_id);
        $parent_menu_id = $data->get('parent_menu_id');

        // get next order
        $order = LeftMenuModel::getNextOrder($parent_menu_id);
        $data->set('`order`',$order);

        $Record =& DBC::NewRecord($data);
        $menu_id =  $Record->insertId('sport_menu',
            array('parent_menu_id', 'page_id','title', 'url', '`order`', 'image',
            'enable', 'type', 'external', 'menu_location','site_id'),
            'menu_id');
        return $menu_id;
    }

    function updateMenu($id, &$data) {
        $site_id = Site::getSiteID();
        $data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_menu',
            array('parent_menu_id', 'page_id','title', 'url', 'image', 'type', 'external','site_id'),
            "menu_id=". DBC::makeLiteral($id));
    }

    function activateMenu($id,  &$data, $flag) {
     	if ($flag)  $data->set('enable',1);
     	else $data->set('enable',0);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_menu',
            array('enable'),
            "menu_id=". DBC::makeLiteral($id));
    }

    // get last order of the menu items with defined parent
    function getLastOrder($parent_id) {
    	$site_id = Site::getSiteID();
    	if (!$parent_id) $parent_id = 0;
    	$order = 0;

        $rec =& DBC::FindRecord("select max(`order`) as max_order from sport_menu
        where parent_menu_id = ". DBC::makeLiteral($parent_id)."
        and site_id = ".DBC::makeLiteral($site_id));
        if ($rec) $order = $rec->get('max_order');
        //print 'Last order for parent_id '.$parent_id.' = '.$order;
        return $order;
    }

    // get order of the menu item
    function getOrder($menu_id) {
    	$order = 0;
    	$rec =& DBC::FindRecord("select `order` from sport_menu
    	where menu_id = ". DBC::makeLiteral($menu_id));
        if ($rec) $order = $rec->get('order');
        return $order;
    }

    // get next order of the menu items with defined parent
    function getNextOrder($parent_id) {
    	$next_order = 0;
    	$last_order = LeftMenuModel::getLastOrder($parent_id);
    	if ( $parent_id ) {
    		if ( $last_order )	$next_order = $last_order + 1;
    		else {
            	$parent_order = LeftMenuModel::getOrder($parent_id);
                $next_order = $parent_order + 1;
    		}
    	} else  $next_order = $last_order + 1000;
    	//print 'Next order for parent_id '.$parent_id.' = '.$next_order;
    	return $next_order;
    }

    function updateMenuOrder($menu_id, $order) {
     	$data =& new DataSpace();
     	$data->set('`order`', $order);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_menu', array('`order`'),
            "menu_id=". DBC::makeLiteral($menu_id));
    }

    // returns the previous record for the given order and parent_menu_id
    function &getPrevMenuItem($order, $parent_id, $current_id, $location) {
        $site_id = Site::getSiteID();
    	if ( !$parent_id ) $parent_id = 0;
        $sql = 'select M.*  from sport_menu M where M.parent_menu_id = '.DBC::makeLiteral($parent_id).'
        and M.`order` <= '.DBC::makeLiteral($order).'
        and M.menu_id <> '.DBC::makeLiteral($current_id).'
        and M.menu_location = '.DBC::makeLiteral($location).'
        and M.site_id = '.DBC::makeLiteral($site_id).'
        order by M.`order` desc';

        $result =& DBC::NewRecordSet($sql);

        $result->reset();
        if ($result->next()) {
        	$data =& $result->export();
        	$data['order'] = $result->get('order');
        }
        else $data = null;
        //print_r( $data );
        return $data;
    }

    // returns the next record for the given order and parent_menu_id
    function &getNextMenuItem($order, $parent_id, $current_id, $location) {
    	if ( !$parent_id ) $parent_id = 0;
    	$site_id = Site::getSiteID();
        $sql = 'select M.* from sport_menu M where M.parent_menu_id = '.DBC::makeLiteral($parent_id).'
        and M.`order` >= '.DBC::makeLiteral($order).'
        and M.menu_id <> '.DBC::makeLiteral($current_id).'
        and M.menu_location = '.DBC::makeLiteral($location).'
        and M.site_id = '.DBC::makeLiteral($site_id).'
        order by M.`order` asc';

        $result =& DBC::NewRecordSet($sql);
        $result->reset();
        if ($result->next()) {
        	$data =& $result->export();
        	$data['order'] = $result->get('order');
        }
        else $data = null;

        return $data;
    }

    function swapMenuItems($menu1_id, $order1, $menu2_id, $order2) {
    	LeftMenuModel::updateMenuOrder($menu1_id, $order2);
        LeftMenuModel::updateMenuOrder($menu2_id, $order1);
    }

    function moveMenuUp($menu_id) {
    	$current_menu =& LeftMenuModel::getRecord($menu_id);
    	$current_order = $current_menu->get('order');
        $menu_location = $current_menu->get('menu_location');
    	//print  'Current Order: '.$current_order;
    	$parent_menu_id = $current_menu->get('parent_menu_id');
    	$prev_menu =&  LeftMenuModel::getPrevMenuItem($current_order, $parent_menu_id, $menu_id, $menu_location);
    	//print gettype( $prev_menu );
    	if ($prev_menu) {
    		//$prev_order =  $prev_menu->get('order');
    		//$prev_menu_id = $prev_menu->get('menu_id');
            $prev_order =  $prev_menu['order'];
            //print  'Prev Order: '.$prev_order;
            $prev_menu_id = $prev_menu['menu_id'];
    	}
        if ($prev_menu_id) LeftMenuModel::swapMenuItems($menu_id,$current_order,$prev_menu_id,$prev_order);
    }

    function moveMenuDown($menu_id) {
    	$current_menu =& LeftMenuModel::getRecord($menu_id);
    	$current_order = $current_menu->get('order');
    	$menu_location = $current_menu->get('menu_location');
    	$parent_menu_id = $current_menu->get('parent_menu_id');
    	$next_menu =&  LeftMenuModel::getNextMenuItem($current_order, $parent_menu_id, $menu_id, $menu_location);
    	if ($next_menu) {
    		//$next_order =  $next_menu->get('order');
    		//$next_menu_id = $next_menu->get('menu_id');
            $next_order =  $next_menu['order'];
            $next_menu_id = $next_menu['menu_id'];
    	}
        if ($next_menu_id) LeftMenuModel::swapMenuItems($menu_id,$current_order,$next_menu_id,$next_order);
    }





}

?>
